﻿using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows.Input;
using GalaSoft.MvvmLight.Command;
using Looptribe.Moodlin8.Model.Api;
using Looptribe.WinRT.Toolkit;

namespace Looptribe.Moodlin8.ViewModel
{
    public class UploadsViewModel : LoadingViewModel
    {
        private readonly ObservableCollection<FileWrapper> _uploads = new ObservableCollection<FileWrapper>();
        public ObservableCollection<FileWrapper> Uploads
        {
            get { return _uploads; }
        }

        public ICommand OpenUploadCommand { get; set; }
        public ICommand UploadFileCommand { get; set; }

        public UploadsViewModel()
        {
            OpenUploadCommand = new RelayCommand<FileWrapper>(ExecuteOpenUpload);
            UploadFileCommand = new RelayCommand(ExecuteUploadFile);
        }

        public async void LoadContent()
        {
            IsLoading = true;
            Uploads.Clear();
            var response = (await Api.GetFilesAsync()).Data;
            IsLoading = false;

            if (response != null && response.Files != null)
                Uploads.AddMany(response.Files.Where(a => !a.IsDir).Select(a => new FileWrapper(a)));
        }

        private async void ExecuteOpenUpload(FileWrapper file)
        {
            await Controller.OpenFileAsync(file.WrappedObject);
        }

        private async void ExecuteUploadFile()
        {
            var file = await Controller.PickFileAsync("*");
            if (file != null)
            {
                var uploadedFile = await Api.UploadFileAsync(file);
                if (uploadedFile.Status == Status.Ok)
                    Uploads.Add(new FileWrapper(uploadedFile.Data));
            }
        }
    }
}
